use strict;
use warnings;

package LifeRay;

sub new()
{
    my ($proto) = @_;
    return bless({
	_LABELS => undef,
	_LABEL_CLASSES => undef
		 }, ref($proto) || $proto);
}

sub query($)
{
    my ($self, $q) = @_;
    open(MYSQL, "echo '${q};' | ./rec-sql|");
    my @fields = ();
    my @rows = ();
    while (<MYSQL>)
    {
	s/[\012\015]*$//;
	my @bits = split(/\t/);
	if (!@fields)
	{
	    @fields = @bits;
	    next;
	}
	my %row = ();
	for (my $i = 0; $i < @fields; ++$i)
	{
	    $row{$fields[$i]} = $bits[$i];
	}
	push(@rows,\%row);
    }
    return @rows;
}

sub fetch_labels($$)
{
    my ($self, $table, $id) = @_;
    $self->_read_labels() if (!defined($self->{_LABELS}));
    die if (!defined($self->{_LABEL_CLASSES}) ||
	    !exists($self->{_LABEL_CLASSES}{$table}));
    my $class = $self->{_LABEL_CLASSES}{$table};
    my $key = "$class-$id";
    return exists($self->{_LABELS}{$key})?@{$self->{_LABELS}{$key}}:();
}

sub _read_labels()
{
    my ($self) = @_;
    print STDERR "Reading asset classes...\n";
    $self->{_LABEL_CLASSES} = { map(($_->{value} => $_->{classNameId}), 
				  $self->query('SELECT classNameId, value FROM classname_')) };
    $self->{_LABELS} = {};
    my %sets = ();
    {
	print STDERR "Reading label sets...\n";
	my @sets = $self->query('SELECT vocabularyId, name, description FROM tagsvocabulary');
	die if grep($_->{description}, @sets);
	%sets = map(($_->{vocabularyId} => $_->{name}), @sets);
    }
    my %names = ();
    print STDERR "Reading label names...\n";
    foreach my $label ($self->query('SELECT vocabularyId, entryId, name FROM tagsentry'))
    {
	my $set_id = $label->{vocabularyId};
	die if (!exists($sets{$set_id}));
	$names{$label->{entryId}} = "$sets{$set_id}: $label->{name}";
    }
    my %asset_labels = ();
    print STDERR "Reading asset labels...\n";
    foreach my $label ($self->query('SELECT * FROM tagsassets_tagsentries'))
    {
	push(@{$asset_labels{$label->{assetId}}}, $label->{entryId});
    }
    print STDERR "Reading asset ids...\n";
    foreach my $asset ($self->query('SELECT assetId, classNameId, classPK FROM tagsasset'))
    {
	my $asset_id = $asset->{assetId};
	my $key = "$asset->{classNameId}-$asset->{classPK}";
	$self->{_LABELS}{$key} =
	    [map($names{$_}, exists($asset_labels{$asset_id})?@{$asset_labels{$asset_id}}:())];
    }
}

1;
